#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/logs/internal-functions"

cmd-logs-default() {
  declare desc="display recent log output"
  declare cmd="logs"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1"

  [[ -z "$APP" ]] && dokku_log_fail "Please specify an app to run the command on"
  verify_app_name "$APP"

  ! (is_deployed "$APP") && dokku_log_fail "App $APP has not been deployed"

  shift 1
  local TEMP=$(getopt -o htqn:p: --long help,tail,quiet,num:,ps: -n 'dokku logs' -- "$@")
  local EXIT_CODE="$?"
  if [[ "$EXIT_CODE" != 0 ]]; then
    fn-logs-usage >&2
    exit 1
  fi
  eval set -- "$TEMP"

  local NUM="100"
  while true; do
    case "$1" in
      -t | --tail)
        local TAIL=true
        shift
        ;;
      -n | --num)
        local NUM="$2"
        shift 2
        ;;
      -p | --ps)
        local PROCESS_TYPE="$2"
        shift 2
        ;;
      -q | --quiet)
        local PRETTY_PRINT=true
        shift
        ;;
      --)
        shift
        break
        ;;
      *) dokku_log_fail "Internal error" ;;
    esac
  done

  DOKKU_SCHEDULER=$(get_app_scheduler "$APP")
  plugn trigger scheduler-logs "$DOKKU_SCHEDULER" "$APP" "$PROCESS_TYPE" "$TAIL" "$PRETTY_PRINT" "$NUM"
}

cmd-logs-default "$@"
